const Controller = require('egg').Controller;
const shortid = require('shortid');
class ShortUrlController extends Controller {
    // 生成短码
    async createUrl() {
        const { ctx } = this;
        const { url } = ctx.request.body;
        const short_id = shortid.generate();
        await ctx.model.ShortUrl.create({ url, short_id });
        ctx.send({ msg: "成功", data: { short_id } })
    }
    // 短码重定向到原链接
    async toOriginUrl() {
        const { ctx } = this;
        const { short_id } = ctx.params;
        console.log(short_id);
        const data = await ctx.model.ShortUrl.findOneAndUpdate({ short_id }, { $inc: { visit_count: 1 } })
        if (data) {
            ctx.redirect(data.url)
        }else{
            ctx.send({code:404,msg:"链接不存在",success:false})
        }
    }
}

module.exports = ShortUrlController;
